package com.suneast.suneaststore.modules.personal.sign;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.suneast.suneaststore.R;
import com.suneast.suneaststore.modules.main.BottomFragment;
import com.suneast.suneaststore.modules.personal.sign.event.AuthCodeGotEvent;
import com.suneast.suneaststore.modules.personal.sign.event.CountDownEvent;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.personal.sign.event.RequestAutoCodeResult;
import com.suneast.suneaststore.modules.personal.sign.event.SignUpResult;
import com.suneast.suneaststore.ui.fragments.BaseFragment;
import com.suneast.suneaststore.util.regex.RegexUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class SignUpFragment extends BaseFragment {
    @Override
    public @LayoutRes
    int setLayout() {
        return R.layout.fragment_sign_up;
    }

    @OnClick({R.id.btn_request_code, R.id.btn_sign_up})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.btn_request_code: {
                if (RegexUtil.isMobile(phoneNumber)) {
                    SignRequestHandler.requestAuthCode(phoneNumber, Flag.CodeType.SIGN_UP);
                } else {
                    Toast.makeText(getContext(), R.string.phone_number_input_error_tip,
                            Toast.LENGTH_SHORT).show();
                }
            }
            break;
            case R.id.btn_sign_up: {
                SignRequestHandler.signUp(phoneNumber, authCode, password);
            }
            break;
        }
    }

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.edit_text_phone_number)
    EditText phoneNumberEdit;

    @BindView(R.id.edit_text_auth_code)
    EditText authCodeEdit;

    @BindView(R.id.edit_text_password)
    EditText passWordEdit;

    @BindView(R.id.btn_request_code)
    Button getCodeBtn;

    @BindView(R.id.btn_sign_up)
    Button signUpBtn;

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        initView();
    }

    @Override
    public void onDestroyView() {
        timer.cancel();
        if (task != null) {
            task.cancel();
        }
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    private String phoneNumber = "";
    private String authCode = "";
    private String password = "";

    private void initView() {
        toolbar.setNavigationOnClickListener(v -> pop());
        phoneNumberEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                phoneNumber = s.toString();
                checkSignUpBtn();
            }
        });
        authCodeEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                authCode = s.toString();
                checkSignUpBtn();
            }
        });
        passWordEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                password = s.toString();
                checkSignUpBtn();
            }
        });
        timer = new Timer();
    }

    private int count = 90;
    private TimerTask task;
    private Timer timer;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCountDown(CountDownEvent event) {
        if (event.getType() == Flag.CodeType.SIGN_UP) {
            if (count > 0) {
                getCodeBtn.setText(count + getResources().getString(R.string.afresh_auto_code));
                count--;
            } else {
                task.cancel();
                getCodeBtn.setEnabled(true);
                getCodeBtn.setText(getResources().getString(R.string.get_auth_code));
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotAuthCode(AuthCodeGotEvent event) {
        password = event.getAuthCode();
        passWordEdit.setText(String.valueOf(password));
        if (phoneNumberEdit.length() > 10 && passWordEdit.length() > 0) {
            signUpBtn.setEnabled(true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRequestAuthCodeResult(RequestAutoCodeResult event) {
        switch (event.getState()) {
            case Flag.Result.SUCCEED: {
                getCodeBtn.setEnabled(false);
                count = 90;
                task = new TimerTask() {
                    @Override
                    public void run() {
                        EventBus.getDefault().post(new CountDownEvent(Flag.CodeType.SIGN_UP));
                    }
                };
                timer.schedule(task, 0, 1000);
            }
            break;
            case Flag.Result.FAILURE: {
                getCodeBtn.setEnabled(true);
                Toast.makeText(_mActivity, "请求验证码失败", Toast.LENGTH_SHORT).show();
            }
            break;
        }
    }

    private void checkSignUpBtn() {
        signUpBtn.setEnabled(phoneNumber.length() == 11
                && authCode.length() == 4 && password.length() >= 6);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSignUpResult(SignUpResult result) {
        if (result.getResult() == Flag.Result.SUCCEED) {
            popTo(BottomFragment.class, false);
        } else {
            if (result.getMsg() != null) {
                Toast.makeText(_mActivity, result.getMsg(), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(_mActivity, "注册失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

}
